/*
 * Copyright (C) 2017-2021
 * All rights reserved, Designed By 深圳中科鑫智科技有限公司
 * Copyright authorization contact 18814114118
 */
package com.shop.cereshop.business.controller;

import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.shop.cereshop.business.annotation.NoRepeatSubmit;
import com.shop.cereshop.business.annotation.NoRepeatWebLog;
import com.shop.cereshop.business.page.member.ProductMember;
import com.shop.cereshop.business.page.product.ShopProductVo;
import com.shop.cereshop.business.page.product.Sku;
import com.shop.cereshop.business.page.shop.Shop;
import com.shop.cereshop.business.page.tool.ToolProduct;
import com.shop.cereshop.business.param.product.*;
import com.shop.cereshop.business.param.tool.ToolSkuParam;
import com.shop.cereshop.business.service.product.CereProductClassifyService;
import com.shop.cereshop.business.service.product.CereProductSkuService;
import com.shop.cereshop.business.service.product.CereShopProductService;
import com.shop.cereshop.business.service.shop.CereShopGroupService;
import com.shop.cereshop.business.utils.ContextUtil;
import com.shop.cereshop.commons.constant.CoReturnFormat;
import com.shop.cereshop.commons.domain.business.CerePlatformBusiness;
import com.shop.cereshop.commons.domain.common.Page;
import com.shop.cereshop.commons.domain.product.CereProductClassify;
import com.shop.cereshop.commons.domain.product.CereShopProduct;
import com.shop.cereshop.commons.domain.product.Classify;
import com.shop.cereshop.commons.domain.product.vo.ShopProductRankingListVo;
import com.shop.cereshop.commons.domain.shop.CerePlatformShop;
import com.shop.cereshop.commons.domain.shop.CereShopGroup;
import com.shop.cereshop.commons.exception.CoBusinessException;
import com.shop.cereshop.commons.result.Result;
import com.shop.cereshop.commons.utils.EmptyUtils;
import com.shop.cereshop.commons.utils.GsonUtil;
import com.shop.cereshop.commons.utils.QRCodeUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.ClassPathResource;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;


import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.util.Collections;
import java.util.List;

/**
 * 商品
 */
@RestController
@RequestMapping("/product")
/**
 * 注解方式生成日志对象，指定topic生成对象类名
 */
@Slf4j(topic = "ProductController")
@Api(value = "商品模块", tags = "商品模块")
public class ProductController {

    @Autowired
    private CereShopProductService cereShopProductService;

    @Autowired
    private CereProductClassifyService cereProductClassifyService;

    @Autowired
    private CereShopGroupService cereShopGroupService;

    @Autowired
    private CereProductSkuService cereProductSkuService;

    /**
     * 小程序appid
     */
    @Value("${weixin.appid}")
    private String appid;

    /**
     * 小程序秘钥
     */
    @Value("${weixin.secret}")
    private String secret;

    /**
     * 商品二维码生成
     */
    @GetMapping(value = "/generateProductQR")
    @ApiOperation(value = "商品二维码生成")
    public Result<String> generateProductQR(Long productId,String page) throws CoBusinessException{
        Long shopId = ContextUtil.getShopId();
        ShopProductVo product = cereShopProductService.getById(productId);
        if (CollectionUtil.isEmpty(product.getSkus())){
            throw new CoBusinessException(CoReturnFormat.HAVE_INVALID_PRODUCT);
        }
        Long skuId = product.getSkus().get(0).getSkuId();

        String accessToken = "";
        try {
            accessToken = QRCodeUtil.postToken(appid, secret);
        } catch (Exception e) {
            throw new CoBusinessException(CoReturnFormat.GENERATE_ACCESSTOKEN_FAIL);
        }
        if (StringUtils.isEmpty(page))
            page = "pages/home/productDetails";
        String suffix = "?shopId="+ shopId +"&productId=" + productId + "&skuId=" + skuId;
        String encode = QRCodeUtil.geWeChatCode("shopId=" + shopId, page + suffix, accessToken);
        if (encode == null){
            throw new CoBusinessException(CoReturnFormat.GENERATE_QR_FAIL);
        }
        return new Result<String>(encode,CoReturnFormat.SUCCESS);
    }

    /**
     * 查询分类层级
     * @return
     */
    @PostMapping(value = "getClassify")
    @ApiOperation(value = "查询分类层级")
    public Result<Classify> getClassify() throws CoBusinessException{
        List<Classify> list=cereProductClassifyService.getClassify();
        return new Result(list);
    }

    /**
     * 添加商品
     * @param param
     * @return
     */
    @PostMapping(value = "/save")
    @NoRepeatSubmit
    @ApiOperation(value = "添加商品")
    @NoRepeatWebLog
    public Result save(@RequestBody @Validated ProductSaveParam param, HttpServletRequest request) throws CoBusinessException{
        //获取当前登录账户
        CerePlatformBusiness user = (CerePlatformBusiness) request.getAttribute("user");
        param.setShopId(ContextUtil.getShopId());
        cereShopProductService.save(param,user);
        return new Result(user.getUsername(),"添加商品", GsonUtil.objectToGson(param));
    }

    /**
     * 修改商品
     * @param param
     * @return
     */
    @PostMapping(value = "update")
    @NoRepeatSubmit
    @ApiOperation(value = "修改商品")
    @NoRepeatWebLog
    public Result update(@RequestBody ProductUpdateParam param, HttpServletRequest request) throws CoBusinessException{
        //获取当前登录账户
        CerePlatformBusiness user = (CerePlatformBusiness) request.getAttribute("user");
        param.setShopId(ContextUtil.getShopId());
        cereShopProductService.update(param,user);
        return new Result(user.getUsername(),"修改商品", GsonUtil.objectToGson(param));
    }
    /**
     * 批量修改修改商品属性
     * @return
     */
    @PostMapping(value = "updateBatch")
    @NoRepeatSubmit
    @ApiOperation(value = "批量修改修改商品属性")
    @NoRepeatWebLog
    public Result updateBatch(@RequestBody List<CereShopProduct> productList, HttpServletRequest request) throws CoBusinessException{
        //获取当前登录账户
        CerePlatformBusiness user = (CerePlatformBusiness) request.getAttribute("user");

        cereShopProductService.updateBatchById(productList);
        return new Result(1,CoReturnFormat.SUCCESS);
    }
    /**
     * 删除商品
     * @param param
     * @return
     */
    @PostMapping(value = "delete")
    @NoRepeatSubmit
    @ApiOperation(value = "删除商品")
    @NoRepeatWebLog
    public Result delete(@RequestBody ProductDeleteParam param, HttpServletRequest request) throws CoBusinessException{
        //获取当前登录账户
        CerePlatformBusiness user = (CerePlatformBusiness) request.getAttribute("user");
        cereShopProductService.delete(param,user);
        return new Result(user.getUsername(),"删除商品", GsonUtil.objectToGson(param));
    }

    /**
     * 批量删除商品
     * @param param
     * @return
     */
    @PostMapping(value = "deleteBatch")
    @NoRepeatSubmit
    @ApiOperation(value = "删除商品")
    @NoRepeatWebLog
    public Result deleteBatch(@RequestBody List<ProductDeleteParam> param, HttpServletRequest request) throws CoBusinessException{
        //获取当前登录账户
        CerePlatformBusiness user = (CerePlatformBusiness) request.getAttribute("user");
        for (ProductDeleteParam deleteParam : param) {
            cereShopProductService.delete(deleteParam,user);
        }
        return new Result(user.getUsername(),"批量删除商品", GsonUtil.objectToGson(param));
    }

    /**
     * 商品上下架
     * @param param
     * @return
     */
    @PostMapping(value = "start")
    @NoRepeatSubmit
    @ApiOperation(value = "商品上下架")
    @NoRepeatWebLog
    public Result start(@RequestBody ProductUpDownParam param, HttpServletRequest request) throws CoBusinessException{
        //获取当前登录账户
        CerePlatformBusiness user = (CerePlatformBusiness) request.getAttribute("user");
        cereShopProductService.start(param,user);
        return new Result(user.getUsername(),"商品上下架", GsonUtil.objectToGson(param));
    }

    /**
     * 商品查询详情
     * @param param
     * @return
     */
    @PostMapping(value = "getById")
    @ApiOperation(value = "商品查询详情")
    public Result<ShopProductVo> getById(@RequestBody ProductGetByIdParam param) throws CoBusinessException{
        ShopProductVo shopProduct=cereShopProductService.getById(param.getProductId());
        return new Result(shopProduct,CoReturnFormat.SUCCESS);
    }

    /**
     * 商品管理查询
     * @param param
     * @return
     */
    @PostMapping(value = "getAll")
    @ApiOperation(value = "商品管理查询")
    public Result<Page<ShopProductVo>> getAll(@RequestBody ProductGetAllParam param) throws CoBusinessException{
        param.setShopId(ContextUtil.getShopId());
        Page page=cereShopProductService.getAll(param);
        return new Result(page);
    }

    /**
     * 商品会员价格数据查询
     * @param param
     * @return
     */
    @PostMapping(value = "getProductMembers")
    @ApiOperation(value = "商品会员价格数据查询")
    public Result<List<ProductMember>> getProductMembers(@RequestBody ProductGetByIdParam param) throws CoBusinessException{
        List<ProductMember> list=cereShopProductService.getProductMembers(param.getProductId());
        return new Result(list);
    }

    /**
     * 商品设置会员价
     * @param param
     * @return
     */
    @PostMapping(value = "setProductMember")
    @ApiOperation(value = "商品设置会员价")
    public Result setProductMember(@RequestBody ProductMemberParam param,HttpServletRequest request) throws CoBusinessException{
        //获取当前登录账户
        CerePlatformBusiness user = (CerePlatformBusiness) request.getAttribute("user");
        cereShopProductService.setProductMember(param);
        return new Result(user.getUsername(),"设置会员价格", GsonUtil.objectToGson(param));
    }
    /**
     * 商品清除会员价
     * @param param
     * @return
     */
    @PostMapping(value = "clearProductMember")
    @ApiOperation(value = "商品清除会员价")
    public Result clearProductMember(@RequestBody ProductGetByIdParam param,HttpServletRequest request) throws CoBusinessException{
        //获取当前登录账户
        CerePlatformBusiness user = (CerePlatformBusiness) request.getAttribute("user");
        cereShopProductService.clearProductMember(param.getProductId());
        return new Result(user.getUsername(),"清除会员价格", GsonUtil.objectToGson(param));
    }
    /**
     * 选择类别查询(根据上级节点查询下级)
     * @return
     */
    @PostMapping(value = "getClassifySelect")
    @ApiOperation(value = "选择类别查询(根据上级节点查询下级)")
    public Result<List<CereProductClassify>> getClassifySelect(@RequestBody ProductGetClassifyParam param) throws CoBusinessException{
        List<CereProductClassify> list=cereProductClassifyService.getClassifySelect(param);
        return new Result(list);
    }

    /**
     * 选择商品分组查询
     * @return
     */
    @PostMapping(value = "getGroupSelect")
    @ApiOperation(value = "选择商品分组查询")
    public Result<List<CereShopGroup>> getGroupSelect(@RequestBody ProductGetGroupParam param) throws CoBusinessException{
        param.setShopId(ContextUtil.getShopId());
        List<CereShopGroup> list=cereShopGroupService.getGroupSelect(param);
        return new Result(list);
    }

    /**
     * 导入商品模板表下载
     * @param response
     */
    @PostMapping(value = "downloadTemplate")
    @ApiOperation(value = "导入商品模板表下载")
    public void downloadTemplate(HttpServletResponse response) throws Exception{
        ClassPathResource resource = new ClassPathResource("static/导入商品模板表.xlsx");
        InputStream in = resource.getInputStream();
        XSSFWorkbook excel= new XSSFWorkbook(in);
        String str = "商品导入模板表";
        response.setContentType("application/vnd.ms-excel;charset=utf-8");
        response.setHeader("Content-disposition", "attachment;filename=" + str +".xlsx");// 默认Excel名称
        response.flushBuffer();
        excel.write(response.getOutputStream());
        excel.close();
    }

    /**
     * 导入商品数据
     * @param file
     * @return
     */
    @PostMapping(value = "importProduct")
    @NoRepeatSubmit
    @ApiOperation(value = "导入商品数据")
    public Result importProduct(MultipartFile file) throws CoBusinessException,Exception{
        if(EmptyUtils.isEmpty(file)){
            return new Result(CoReturnFormat.NOT_FILE);
        }
        Workbook wb= WorkbookFactory.create(file.getInputStream());
        cereShopProductService.importProduct(wb);
        return new Result();
    }

    /**
     * 商品规格查询
     * @return
     */
    @PostMapping(value = "getSkus")
    @ApiOperation(value = "商品规格查询")
    public Result<List<ToolProduct>> getToolSkus(@RequestBody ToolSkuParam param) throws CoBusinessException{
        List<ToolProduct> list=cereProductSkuService.getToolSkus(param.getProductId());
        return new Result(list);
    }


    /**
     * 商品排行榜
     * @return
     */
    @GetMapping(value = "productRankList")
    @ApiOperation(value = "商品排行榜")
    public Result< List<ShopProductRankingListVo> > productRankList(String startTime, String endTime,Integer sortType) throws CoBusinessException{
        Long shopId = ContextUtil.getShopId();
        return new Result(cereShopProductService.productRankList(startTime,endTime,shopId,sortType),CoReturnFormat.SUCCESS);
    }

    public static void main(String[] args) {

        String jsonStr = "{\"productName\":\"水龙头12\",\"productBrief\":\"1111\",\"shopGroupId\":148,\"classifyId\":822,\"supplierName\":\"\",\"ifLogistics\":1,\"shelveState\":1,\"ifOversold\":1,\"ifCredit\":1,\"creditLimit\":89999,\"ifHuabei\":1,\"productText\":\"\",\"images\":[{\"imgPath\":\"https://zhiwushibie.oss-cn-heyuan.aliyuncs.com/test/2022-08-10/785cecd12ac04ba5b2d964b076172639_u=3015928106,2363858851&fm=253&fmt=auto&app=138&f=JPEG.jpg\",\"uid\":1660102500021,\"status\":\"success\"}],\"deletes\":[],\"names\":[{\"code\":\"attr_code_0\",\"skuName\":\"尺寸\",\"needImg\":false,\"values\":[{\"skuValue\":\"20\",\"valueCode\":\"attr_code_0_value_0\",\"image\":\"\"},{\"skuValue\":\"30\",\"valueCode\":\"attr_code_0_value_1\",\"image\":\"\"}]},{\"code\":\"attr_code_1\",\"skuName\":\"颜色\",\"values\":[{\"skuValue\":\"黄色\",\"valueCode\":\"attr_code_1_value_0\",\"image\":\"\",\"isDelete\":0,\"sortOrder\":0},{\"skuValue\":\"银色\",\"valueCode\":\"attr_code_1_value_1\",\"image\":\"\"}],\"isDelete\":0,\"needImg\":0,\"sortOrder\":0}],\"skus\":[{\"isDelete\":\"\",\"skuAttrCodeDTOList\":[{\"code\":\"attr_code_0\",\"valueCode\":\"attr_code_0_value_0\"},{\"code\":\"attr_code_1\",\"valueCode\":\"attr_code_1_value_0\"}],\"skuAttrList\":[],\"sku\":\"\",\"skuImg\":\"\",\"price\":20,\"originalPrice\":10,\"stockNumber\":999,\"weight\":1,\"style\":1},{\"isDelete\":\"\",\"skuAttrCodeDTOList\":[{\"code\":\"attr_code_0\",\"valueCode\":\"attr_code_0_value_0\"},{\"code\":\"attr_code_1\",\"valueCode\":\"attr_code_1_value_1\"}],\"skuAttrList\":[],\"sku\":\"\",\"skuImg\":\"\",\"price\":30,\"originalPrice\":20,\"stockNumber\":999,\"weight\":1,\"style\":1},{\"isDelete\":\"\",\"skuAttrCodeDTOList\":[{\"code\":\"attr_code_0\",\"valueCode\":\"attr_code_0_value_1\"},{\"code\":\"attr_code_1\",\"valueCode\":\"attr_code_1_value_0\"}],\"skuAttrList\":[],\"sku\":\"\",\"skuImg\":\"\",\"price\":40,\"originalPrice\":30,\"stockNumber\":999,\"weight\":1,\"style\":1},{\"isDelete\":\"\",\"skuAttrCodeDTOList\":[{\"code\":\"attr_code_0\",\"valueCode\":\"attr_code_0_value_1\"},{\"code\":\"attr_code_1\",\"valueCode\":\"attr_code_1_value_1\"}],\"skuAttrList\":[],\"sku\":\"\",\"skuImg\":\"\",\"price\":50,\"originalPrice\":40,\"stockNumber\":999,\"weight\":1,\"style\":1}]}";
        JSONObject jsonObject = JSON.parseObject(jsonStr);
        System.out.println(JSON.toJSONString(jsonObject, SerializerFeature.PrettyFormat));
    }
}
